//
//  TJStatus.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/12.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class TJStatus: NSObject {

    
    // 微博创建时间.
    var created_at:String?
    
    // 微博的id.
    var id:Int64 = 0
    
    //微博的内容.
    var text:String?
    
    // 微博的来源.
    var source:String? {
    
        didSet {
        
            if let newScource = source {
            
                let firstRange = newScource.rangeOfString("\">")
                let lastRange = newScource.rangeOfString("</a>")
                guard let startIndex = firstRange?.endIndex else {
                
                    TJPrint("没有匹配到来源")
                    return
                }
                guard let endIndex = lastRange?.startIndex else {
                    
                    TJPrint("没有匹配到来源")
                    return
                }
                let sourceRange = startIndex ..< endIndex
                source = "来自" + newScource.substringWithRange(sourceRange)
            }
        }
    }
    
    // 微博配图.是一个字典数组.
    var pic_urls:[[String: AnyObject]]? {
    
        didSet {
            
            if pic_urls?.count != 0 {
                
                // 遍历数组,将sring转成url,存入数组中.
                picURLS = [NSURL]()
                for dict in pic_urls! {
                
                    let url = NSURL(string: dict["thumbnail_pic"] as! String)
                    picURLS?.append(url!)
                }
            
               
            }
        }
    }
    
    // 配图URL数组-->供外界直接使用.
    var picURLS:[NSURL]?
    
    // 用户模型,服务器返回的是字典,需要自己转成模型.
    var user:TJUser?
    
    // 被转发微博模型.
    var retweeted_status:TJStatus?
    
    // 保存cell的行高.
    var rowHeight:CGFloat?
    
    // KVC的原理:dict有多少个key就会调用setvalue:forkey/undfineKey:多少次,找打与模型对应的属性就调用forkye,找不到就调用forunderinedKey.
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // 重写setValue:forkey:对user属性拦截,进行字典转模型.
    override func setValue(value: AnyObject?, forKey key: String) {
        // 拦截user,字典转模型.
        if key == "user" {
        
            if let dict = value as? [String:AnyObject] {
                user = TJUser(dict: dict)
            }
            return
        }
        
        // 拦截retweeted_status,将被转发微博进行字典转模型.
        if key == "retweeted_status" {
        
            if let dict = value as? [String:AnyObject] {
            
                retweeted_status = TJStatus(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    // 空实现undefineKey.
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 打印对象信息.
    override var description:String {
    
        get {
        
            let keys = ["created_at","id","text","source","pic_urls","user"]
            return "微博模型:\(dictionaryWithValuesForKeys(keys).description)"
        }
    }
}
